package com.lv.servlet;

import com.google.gson.Gson;
import com.lv.bean.DUser;
import com.lv.bean.User;
import com.lv.dao.UserDao;
import com.lv.dao.UserDaoImpl;
import com.lv.service.UserService;
import com.lv.service.UserServiceImpl;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String data = request.getParameter("data");
        String flag = request.getParameter("flag");
        Gson gson = new Gson();
        DUser dUser = gson.fromJson(data, DUser.class);
        if (dUser.getAdmin() == null) {
            dUser.setAdmin(0);
        }
        User user = new User(dUser.getUserid(), dUser.getName(), dUser.isActive(), dUser.getAvatar(), dUser.getDepartment().toString(), dUser.getMobile(), dUser.getAdmin());
        String userId = dUser.getUserid();
        String name = dUser.getName();
        request.getSession().setAttribute("userId", userId);
        request.getSession().setAttribute("userId", name);
        UserDao userDao = new UserDaoImpl();
        User u = userDao.selectUserId(userId);//根据当前用户id去数据库中查询得到的用户
        response.setContentType("text/javascript");
        if (u == null) {//第一次
            UserService userService = new UserServiceImpl();
            boolean isInsert = userService.insertUser(user);
            if (isInsert) {
                if (flag != null && "0".equals(flag)) {//PC端
                    //判断是不是管理员

                    response.getWriter().print("true");
                } else {
                    response.getWriter().print("true");
                }

            } else {
                response.getWriter().print("false");
            }
        } else {//非第一次
            if (flag != null && "0".equals(flag)) {//PC端
                //判断是不是管理员
                response.getWriter().print("true");
            } else {
                response.getWriter().print("true");
            }
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        this.doGet(req, resp);
    }
}
